/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState } from 'react';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbApplyModal from '@/components/_pages/Finance/approval/components/KbApplyModal';
import KbOpenDetailModal from '@/components/_pages/Finance/approval/components/KbOpenDetailModal';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { openPlatFormColumns } from '@/components/_pages/Finance/index.config';
import type { ConnectState } from '@/models/connect';
import { openInvoiceList, openInvoiceRechargeStatusEdit } from '@/services/Finance/approval';
import { useSelector } from 'umi';
import { message, Space, Popconfirm, Tooltip, Button, Modal } from 'antd';
import QueryString from 'qs';
import styles from './index.less';

const Index: React.FC = () => {
  const [visible, setVisible] = useState<boolean>(false);
  const [recordItem, setRecordItem] = useState<{ [name: string]: string }>({});
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const { winSize } = useSelector((state: ConnectState) => state.global);

  const handleOpenModal = (record: { [name: string]: string }) => {
    setRecordItem(record);
    setVisible(true);
  };
  const handleCloseModal = () => {
    setRecordItem({});
    setVisible(false);
  };
  const handleAdopt = (record: { [name: string]: string }) => {
    openInvoiceRechargeStatusEdit({ id: record.id, status_invoice: 1 }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('提交成功');
        setVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };
  const handleFail = () => {
    setVisible(false);
    actionRef.current?.reload();
  };

  const handleMessageInfo = (info: string) => {
    Modal.info({
      icon: null,
      title: '拒绝原因',
      content: <div>{info}</div>,
    });
  };

  const columns: ProColumns[] = [
    ...openPlatFormColumns(formRef, 'examine'),
    {
      title: '邮递信息',
      dataIndex: 'transfer_money',
      width: 200,
      search: false,
      align: 'center',
      ellipsis: true,
      render: (_, record) => {
        const { receiver_name, receiver_phone, receiver_address } = record;
        if (!receiver_name && !receiver_phone && !receiver_address) {
          return '-';
        }
        return (
          <Tooltip title={receiver_name + receiver_phone + receiver_address}>
            <Space direction='vertical'>
              <div>
                {receiver_name} {receiver_phone}
              </div>
              <div>{receiver_address}</div>
            </Space>
          </Tooltip>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: winSize === 'xs' ? 60 : 140,
      fixed: 'right',
      align: 'center',
      render: (_, record) => {
        const { id, status_invoice, reason } = record;
        return (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            <a onClick={handleOpenModal.bind(null, record)}>详情</a>
            {`${status_invoice}` === '0' || `${status_invoice}` === '2' ? (
              <Popconfirm title='你确定审核通过？' onConfirm={handleAdopt.bind(null, record)}>
                <a>通过</a>
              </Popconfirm>
            ) : null}
            {`${status_invoice}` === '0' ? (
              <KbApplyModal
                onCallBack={handleFail}
                submit={openInvoiceRechargeStatusEdit}
                queryData={{ id: id, status_invoice: 2 }}
                name='reason'
              >
                <a>拒绝</a>
              </KbApplyModal>
            ) : null}
            {`${status_invoice}` === '2' ? (
              <a onClick={handleMessageInfo.bind(null, reason)}>查看原因</a>
            ) : null}
          </Space>
        );
      },
    },
  ];

  const onDownload = () => {
    const query = QueryString.stringify(formRef.current?.getFieldsValue());
    window.open('/invoice/openInvoiceDownloadExcel?' + query, '_self');
  };
  const onFinish = async (values: any) => {
    const { current: page, pageSize: size } = values;
    delete values.current;
    delete values.pageSize;
    const { code, data, msg } = await openInvoiceList({ ...values, page, size });
    if (code == 0) {
      const { list, count, total = 1 * count } = data;
      return {
        data: list,
        total: total,
      };
    }
    message.error(msg);
    return {
      data: [],
    };
  };
  return (
    <>
      <DragTable>
        <ProTable
          className={styles.main}
          actionRef={actionRef}
          formRef={formRef}
          rowKey='id'
          request={onFinish}
          columns={columns}
          options={false}
          scroll={{ x: 2100 }}
          pagination={{
            pageSize: 20,
            showSizeChanger: false,
          }}
          search={{
            collapseRender: () => <></>,
            collapsed: false,
            optionRender: (_, __, dom) => [
              ...dom.reverse(),
              <Button key='download' type='primary' style={{ marginLeft: 20 }} onClick={onDownload}>
                下载
              </Button>,
            ],
          }}
        />
      </DragTable>
      <KbOpenDetailModal
        visible={visible}
        recordItem={recordItem}
        onVisibleChange={handleCloseModal}
      />
    </>
  );
};

export default Index;
